package com.jvm.classfile.model;

import com.jvm.Utils;

import java.util.Objects;

/**
 * @program: diy_simple_jvm
 * @description: 实例，虚拟机内部产生的所有实例对象
 * @author: CaoYong
 * @create: 2021-07-09 15:46
 **/
public class Instance {

    /**
     * 类,模板
     */
    Class clazz;

    /**
     * 字段
     */
    Field[] fields;

    /**
     * 父实例
     */
    Instance superInstance;

    public Instance(Class clazz) {
        this.clazz = clazz;
    }

    public Instance() {
    }

    /**
     * 获取实例字段，递归获取
     */
    public Field getField(String name, String descriptor) {
        for (Field field : fields) {
            if (Utils.isStatic(field.getAccessFlag())) {
                continue;
            }
            if (Objects.equals(name, field.name) && Objects.equals(descriptor, field.descriptor)) {
                return field;
            }
        }

        if (superInstance == null) {
            return null;
        }

        return superInstance.getField(name, descriptor);
    }
}
